//! Phase 1 性能基准测试
//!
//! 验证核心引擎的基础性能指标

use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};
use cdb::sql::Value;
use cdb::storage::index::{BTreeIndex, HashIndex, Index};
use cdb::utils::metrics::MetricsCollector;
use std::time::Duration;



/// 内存管理基准测试
fn benchmark_memory_management(c: &mut Criterion) {
    use cdb::config::DatabaseConfig;
    use cdb::storage::memory::MemoryManager;
    
    let config = DatabaseConfig::default();
    let memory_manager = MemoryManager::new(&config).unwrap();
    
    c.bench_function("memory_page_allocation", |b| {
        b.iter(|| {
            let page_id = memory_manager.allocate_page().unwrap();
            memory_manager.deallocate_page(page_id).unwrap();
        });
    });
    
    c.bench_function("memory_page_write_read", |b| {
        let page_id = memory_manager.allocate_page().unwrap();
        let test_data = vec![1u8; 1024]; // 1KB数据
        
        b.iter(|| {
            memory_manager.write_page(page_id, black_box(test_data.clone())).unwrap();
            let _data = memory_manager.get_page(page_id).unwrap();
        });
        
        memory_manager.deallocate_page(page_id).unwrap();
    });
}

/// SQL解析基准测试
fn benchmark_sql_parsing(c: &mut Criterion) {
    use cdb::sql::parser::SqlParser;
    
    let parser = SqlParser::new();
    let queries = vec![
        "SELECT id, name FROM users",
        "SELECT * FROM users WHERE age > 18",
        "INSERT INTO users VALUES (1, 'Alice', 25)",
        "UPDATE users SET name = 'Bob' WHERE id = 1",
        "DELETE FROM users WHERE id = 1",
        "CREATE TABLE test (id INTEGER, name VARCHAR(50))",
    ];
    
    for (i, query) in queries.iter().enumerate() {
        c.bench_with_input(
            BenchmarkId::new("sql_parsing", i),
            query,
            |b, query| {
                b.iter(|| {
                    parser.parse(black_box(query)).unwrap();
                });
            },
        );
    }
}

/// 索引操作基准测试
fn benchmark_index_operations(c: &mut Criterion) {
    let mut group = c.benchmark_group("index_operations");
    
    // B+树索引基准测试
    group.bench_function("btree_index_insert", |b| {
        let mut index = BTreeIndex::new("test_column".to_string());
        let mut counter = 0i64;
        
        b.iter(|| {
            index.insert(Value::Integer(counter), counter as usize).unwrap();
            counter += 1;
        });
    });
    
    // 哈希索引基准测试
    group.bench_function("hash_index_insert", |b| {
        let mut index = HashIndex::new("test_column".to_string());
        let mut counter = 0i64;
        
        b.iter(|| {
            index.insert(Value::Integer(counter), counter as usize).unwrap();
            counter += 1;
        });
    });
    
    // 索引查找基准测试
    group.bench_function("btree_index_lookup", |b| {
        let mut index = BTreeIndex::new("test_column".to_string());
        
        // 预填充数据
        for i in 0..1000 {
            index.insert(Value::Integer(i), i as usize).unwrap();
        }
        
        b.iter(|| {
            let key = Value::Integer(black_box(500));
            index.lookup(&key).unwrap();
        });
    });
    
    group.finish();
}

/// 指标收集基准测试
fn benchmark_metrics_collection(c: &mut Criterion) {
    let collector = MetricsCollector::new();
    
    c.bench_function("metrics_query_recording", |b| {
        let query_metrics = collector.query_metrics();
        
        b.iter(|| {
            let timer = query_metrics.query_started();
            std::thread::sleep(Duration::from_nanos(100)); // 模拟查询时间
            timer.finish(true, Duration::from_millis(100));
        });
    });
    
    c.bench_function("metrics_storage_recording", |b| {
        let storage_metrics = collector.storage_metrics();
        
        b.iter(|| {
            storage_metrics.record_read(black_box(1024));
            storage_metrics.record_write(black_box(512));
            storage_metrics.record_cache_hit();
        });
    });
}



/// 配置系统基准测试
fn benchmark_configuration(c: &mut Criterion) {
    use cdb::utils::config::{Config, ConfigBuilder};
    use tempfile::NamedTempFile;
    
    c.bench_function("config_creation", |b| {
        b.iter(|| {
            ConfigBuilder::new()
                .memory_limit(black_box(1024 * 1024 * 1024))
                .max_connections(black_box(100))
                .postgres_port(black_box(5432))
                .build()
                .unwrap();
        });
    });
    
    c.bench_function("config_serialization", |b| {
        let config = Config::default();
        let temp_file = NamedTempFile::new().unwrap();
        
        b.iter(|| {
            config.save_to_file(temp_file.path()).unwrap();
            Config::from_file(temp_file.path()).unwrap();
        });
    });
}

criterion_group!(
    benches,
    benchmark_memory_management,
    benchmark_sql_parsing,
    benchmark_index_operations,
    benchmark_metrics_collection,
    benchmark_configuration
);

criterion_main!(benches);
